package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.message.NewsAutoScanConstants;
import com.heima.common.constants.message.WmNewsMessageConstants;
import com.heima.common.constants.wemedia.WemediaConstants;
import com.heima.common.exception.CustException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDto;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import io.seata.common.util.CollectionUtils;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${file.oss.web-site}")
    String webSite;

    @Override
    public ResponseResult findList(WmNewsPageReqDto dto) {
        dto.checkParam();
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.<WmNews>lambdaQuery();
        queryWrapper.like(StringUtils.isNotBlank(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
        queryWrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
        queryWrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
        queryWrapper.ge(dto.getBeginPubDate() != null, WmNews::getCreatedTime, dto.getBeginPubDate());
        queryWrapper.le(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());
        queryWrapper.eq(WmNews::getUserId, user.getId());
        queryWrapper.orderByDesc(WmNews::getPublishTime);
        IPage<WmNews> pageReq = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmNews> pageResult = page(pageReq, queryWrapper);
        PageResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), pageResult.getTotal());
        result.setData(pageResult.getRecords());
        result.setHost(webSite);
        return result;
    }
    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;
@Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        if (StringUtils.isBlank(wmNewsDto.getContent())) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章内容不能为空");
        }
        Short status = wmNewsDto.getStatus();
        if (status == null && status.intValue() != 0 && status.intValue() != 1) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "文章状态错误");
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(wmNewsDto, wmNews);//拷贝属性
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        if (CollectionUtils.isNotEmpty(wmNewsDto.getImages())) {
            String imageStr = imageListTostr(wmNewsDto.getImages());
            wmNews.setImages(imageStr);
        }
        wmNews.setUserId(user.getId());
        saveOrUpdateWmNews(wmNews);
        if (status.intValue() == 0) {
            ResponseResult.okResult();
        }
        List<String> constantsImages = parseContentImages(wmNews.getContent());
        if (CollectionUtils.isNotEmpty(constantsImages)) {
            saveRelativeInfo(constantsImages, wmNews.getId(), WemediaConstants.WM_IMAGE_REFERENCE);
            log.info("文章自动审核消息已发送成功 文章id：{}",wmNews.getId());

        }
        saveRelativeInfoForCover(constantsImages, wmNews, wmNewsDto);
    HashMap hashMap = new HashMap();
    hashMap.put("newsId",wmNews.getId());
    kafkaTemplate.send(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_TOPIC, JSON.toJSONString(hashMap));
        return ResponseResult.okResult();

    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null) {
          CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNews);
        responseResult.setHost(webSite);

        return  responseResult;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult delNews(Integer id) {
        if (id==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = getById(id);
        if (wmNews==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())&&wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"该文章已发布并且上架，无法删除");
        }
        removeById(id);
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,id));
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        if(dto.getId()==null||dto.getEnable()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable=dto.getEnable();
        if (enable.intValue()!=0&&enable.intValue()!=1){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"上下架状态错误");
        }
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!wmNews.getStatus().equals(WemediaConstants.WM_NEWS_PUBLISH_STATUS)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"当前文章不是发布状态，无法上下架");
        }
        wmNews.setEnable(enable);
        updateById(wmNews);
        if(wmNews.getArticleId()!=null){
            Map<String,Object> mesMap = new HashMap<>();
            mesMap.put("enable",dto.getEnable());
            mesMap.put("articleId",wmNews.getArticleId());
            kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(mesMap));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    @Override
    public ResponseResult<List<Integer>> findRelease() {
        List<WmNews> list = list(Wrappers.<WmNews>lambdaQuery().in(WmNews::getStatus, 4, 8)
                .le(WmNews::getPublishTime, new Date())
                .select(WmNews::getId));
        List<Integer> newsIdList = list.stream().map(WmNews::getId).collect(Collectors.toList());

        return ResponseResult.okResult(newsIdList);
    }
@Autowired
WmNewsMapper wmNewsMapper;
    @Override
    public ResponseResult findList(NewsAuthDto dto) {
        dto.checkParam();
        Integer currentPage = dto.getPage();
        dto.setPage((currentPage-1)*dto.getSize());
        if (StringUtils.isNotBlank(dto.getTitle())) {
            dto.setTitle("%"+dto.getTitle()+"%");
        }
        List<WmNewsVo> listAndPage = wmNewsMapper.findListAndPage(dto);
        long listCount = wmNewsMapper.findListCount(dto);
        PageResponseResult responseResult = new PageResponseResult(currentPage,dto.getSize(),listCount);
            responseResult.setData(listAndPage);
        return responseResult;
    }

    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        if(id == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"id不能为空");
        }
        WmNewsVo wmNewsVo = wmNewsMapper.findWmNewsById(id);
        if (wmNewsVo==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(webSite);
        return responseResult;
    }

    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDto dto) {
        if(dto.getId()==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        wmNews.setStatus(status);
        if (StringUtils.isNotBlank(dto.getMsg())) {
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);
        return ResponseResult.okResult();
    }

    private void saveRelativeInfoForCover(List<String> constantsImages, WmNews wmNews, WmNewsDto wmNewsDto) {
        List<String> images = wmNewsDto.getImages();
        if (wmNewsDto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            if (CollectionUtils.isEmpty(constantsImages)) {
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
                images = null;
            } else if (constantsImages.size() <= 2) {
                wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images = constantsImages.stream().limit(1).collect(Collectors.toList());
            } else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images = constantsImages.stream().limit(3).collect(Collectors.toList());
            }
            if(CollectionUtils.isNotEmpty(images)){
                wmNews.setImages(imageListTostr(images));
            }

            updateById(wmNews);

        }
        if(CollectionUtils.isNotEmpty(images)){
            images.stream().map(url -> url.replaceAll(webSite,"")).collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }


    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;

    private void saveRelativeInfo(List<String> materialUrls, Integer newsId, Short type) {
        List<WmMaterial> wmMaterials = wmMaterialMapper.selectList(
                Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, materialUrls)
                        .eq(WmMaterial::getUserId, WmThreadLocalUtils.getUser().getId())

        );
        if (CollectionUtils.isEmpty(wmMaterials)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "引用的素材不存在");
        }

        Map<String, Integer> urlAndIdMap = wmMaterials.stream().collect(Collectors.toMap(WmMaterial::getUrl, WmMaterial::getId));
        List<Integer> materialIds = new ArrayList();
        materialUrls.forEach(url -> {
            if (!urlAndIdMap.containsKey(url)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "引用的素材不存在");
            }
            materialIds.add(urlAndIdMap.get(url));
        });
        wmNewsMaterialMapper.saveRelations(materialIds, newsId, type);
    }

    private List<String> parseContentImages(String content) {
        List<Map> contentMap = JSONArray.parseArray(content, Map.class);
        List<String> imageList = contentMap.stream()
                .filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .map(url -> url.replaceAll(webSite, ""))
                .collect(Collectors.toList());

        return imageList;
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    private void saveOrUpdateWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);
        }
    }

    private String imageListTostr(List<String> images) {
        return images.stream().map(str -> str.replaceAll(webSite, "")).collect(Collectors.joining(","));
    }
}
